<template>
  <div class="pagination">
    <!-- 前半部分 -->
    <button :disabled="pageNo === 1" @click="$emit('getPageNo', pageNo - 1)">
      上一页
    </button>
    <button
      :class="{ active: pageNo === 1 }"
      v-if="startAndEnd.start > 1"
      @click="$emit('getPageNo', 1)"
    >
      1
    </button>
    <button v-if="startAndEnd.start > 2">···</button>

    <!-- 中间连续页 -->
    <button
      v-for="(page, index) in startAndEnd.end"
      :key="index"
      :class="{ active: pageNo === page }"
      v-show="page >= startAndEnd.start"
      @click="$emit('getPageNo', page)"
    >
      {{ page }}
    </button>

    <!-- 后半部分 -->
    <button v-if="startAndEnd.end < totalPage - 1">···</button>
    <button
      :class="{ active: pageNo === totalPage }"
      v-if="startAndEnd.end < totalPage"
      @click="$emit('getPageNo', totalPage)"
    >
      {{ totalPage }}
    </button>
    <button :disabled="pageNo === totalPage" @click="$emit('getPageNo', pageNo + 1)">
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: ['pageNo', 'pageSize', 'total', 'continues'],
  computed: {
    //总共页数
    totalPage() {
      //向上取整
      return Math.ceil(this.total / this.pageSize)
    },
    //计算出连续页码的起始页码和结束页码
    startAndEnd() {
      //先定义两个变量，存储起始和结束页码
      let start = 0
      let end = 0
      //总页数小于连续页数
      if (this.continues > this.totalPage) {
        start = 1
        end = this.totalPage
      } else {
        start = this.pageNo - (this.continues - 1) / 2
        end = this.pageNo + (this.continues - 1) / 2
        //如果起始页码算出来小于1，则使它等于1，且结束页码为 连续页
        if (start < 1) {
          start = 1
          end = this.continues
        }
        //如果结束页码算出来大于总页码，则使它等于总页码，且起始页码为 总页码 - 连续页
        if (end > this.totalPage) {
          end = this.totalPage
          start = end - this.continues
        }
      }
      return { start, end }
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #e1251b;
      color: #fff;
    }
  }
}
</style>
